<template>
  <view class="message-audio" :class="['content content-' + message.flow]"  @click="handlePlay">
    <image v-if="message.flow==='in'" class="audio-icon audio-icon-in" :src="data.isPlay ? audioPlayImg : audioImg"></image>
		<view>{{data.second}}s</view>
		<image v-if="message.flow==='out'" class="audio-icon " :src="data.isPlay ? audioPlayImg : audioImg"></image>
 </view>
</template>

<script lang="ts">
import { defineComponent, watchEffect, reactive, toRefs, ref, onMounted } from 'vue';
import audioImg from '../../../../assets/audio.png';
import audioPlayImg from '../../../../assets/audio-play.gif';

const audio = uni.createInnerAudioContext();
const MessageAudio = defineComponent({
  props: {
    data: {
      type: Object,
      default: () => {
        return {};
      }
    },
		messageData: {
			type: Object,
			default: () => {
				return {};
			}
		}
  },
  setup(props:any, ctx:any) {
    const data = reactive({
      data: {
        isPlay: false,
        url: ""
      },
			message: {
        flow: ""
      }
    });
		
    watchEffect(()=>{
      data.data = props.data;
			data.message = props.messageData;
    });
		
		onMounted(() => {
			audio.onPlay(() => {
        // 播放并关闭其它语音-仅控制图标
        data.data.isPlay = (audio.src === data.data.url ? true : false);
			});
			audio.onEnded(() => {
        if(audio.src === data.data.url){
          data.data.isPlay = false;
        }
			});
			audio.onError(e => {
				console.error(e, 'onError');
				// ios 音频播放无声，可能是因为系统开启了静音模式
				uni.showToast({
					icon: 'none',
					title: '该音频暂不支持播放'
				});
			});
			
		})
		
    const handlePlay = () => {
			if (data.data.url) {
				audio.src = data.data.url;
				audio.play();
			}
    };

    return {
      ...toRefs(data),
      audio,
      handlePlay,
      audioImg,
      audioPlayImg
    };
  }
});
export default MessageAudio
</script>
<style lang="scss" scoped>
.message-audio {
  display: flex;
	width: 160rpx;
  align-items: center;
  position: relative;
	.audio-icon {
		width: 20px;
		height: 20px;
		padding: 0 5px;
	}
	.audio-icon-in {
		transform: rotate(180deg)
	}
  audio {
    width: 0;
    height: 0;
  }
}
.content {
		padding: 10px;
    &-in {
      background: #e1e1e1;
      border-radius: 0px 10px 10px 10px;
      justify-content: flex-start;
    }
    &-out {
      background: #DCEAFD;
      border-radius: 10px 0px 10px 10px;
      justify-content: flex-end;
    }
  }
</style>
